package com.shjy.driver.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.shjy.driver.R;
import com.shjy.driver.delegate.MainWebviewDelegate;
import com.shjy.driver.jg.JGUtil;
import com.shjy.driver.service.LocationService;
import com.shjy.driver.util.Const;
import com.shjy.driver.xf.XFUtil;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends AppCompatActivity {

    private TextView menuHome;
    private TextView menuOrder;
    private TextView menuMe;
    private WebView mWebView;

    private int currentMenu;
    private long currentTimeMillis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.activity_main);

        // 初始化 Webview
        initWebview();

        // 初始化 底部导航栏
        initBottomNavigationBar();

        // 初始化 第三方SDK
        initThirdFrameworks();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        IntentFilter screenStateFilter = new IntentFilter();
//        screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
//        screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
//        registerReceiver(MyBroadCastReciever, screenStateFilter);

        SharedPreferences sharedPreferences = this.getSharedPreferences("cookie", Context.MODE_PRIVATE);
        final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");

        SharedPreferences sharedPreferencesFirst = this.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sharedPreferencesFirst.edit();
        editor.putString("firstLoad_"+driverUuid,"0");
        editor.commit();

    }

    BroadcastReceiver MyBroadCastReciever = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Log.i("application", "Screen went OFF");
                //Toast.makeText(context, "screen OFF", Toast.LENGTH_LONG).show();
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                Log.i("application", "Screen went ON");

                //Toast.makeText(context, "screen ON", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    public void onBackPressed() {

        String[] urls = new String[]{Const.URL_HOME, Const.URL_ORDERLIST, Const.URL_ME};
        boolean canGoBack = !mWebView.getUrl().equals(urls[currentMenu]) && mWebView.canGoBack();

        if (canGoBack) {
            mWebView.goBack();
        } else {
            if (System.currentTimeMillis() - currentTimeMillis > 2000) {
                Toast.makeText(MainActivity.this, "再点一次退出程序", Toast.LENGTH_SHORT).show();
                currentTimeMillis = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    /**
     * 初始化 Webview
     */
    private void initWebview() {

        mWebView = (WebView) findViewById(R.id.webview);

        // 优先使用缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new MainWebChromeClient());
        mWebView.setWebViewClient(new MainWebViewClient());
        mWebView.addJavascriptInterface(new MainWebviewDelegate(this), "delegate");

        // 默认加载首页
        mWebView.loadUrl(Const.URL_HOME);
    }

    /**
     * 初始化 底部导航栏
     */
    private void initBottomNavigationBar() {

        menuHome = (TextView) findViewById(R.id.menu_home);
        menuOrder = (TextView) findViewById(R.id.menu_order);
        menuMe = (TextView) findViewById(R.id.menu_me);

        resetBottomNavigationBar();

        // 首页
        menuHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 跳转到首页
                mWebView.loadUrl(Const.URL_HOME);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuHome.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuHome.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_home_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuHome.setCompoundDrawables(null, drawable, null, null);

                currentMenu = 0;
            }
        });
        // 订单
        menuOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 跳转到订单列表页
                mWebView.loadUrl(Const.URL_ORDERLIST);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuOrder.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuOrder.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_order_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuOrder.setCompoundDrawables(null, drawable, null, null);

                currentMenu = 1;
            }
        });

        // 我的
        menuMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 跳转到个人页
                mWebView.loadUrl(Const.URL_ME);

                // 重新设定底部导航栏
                resetBottomNavigationBar();
                menuMe.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
                Drawable[] drawables = menuMe.getCompoundDrawables();
                Drawable drawable = getResources().getDrawable(R.drawable.i_me_selected);
                drawable.setBounds(drawables[1].getBounds());
                menuMe.setCompoundDrawables(null, drawable, null, null);

                currentMenu = 2;
            }
        });

        // 默认首页
        menuHome.setTextColor(getResources().getColor(R.color.colorBottomMenuSelected));
        Drawable[] drawables = menuHome.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_home_selected);
        drawable.setBounds(drawables[1].getBounds());
        menuHome.setCompoundDrawables(null, drawable, null, null);

        currentMenu = 0;
    }

    /**
     * 重置 底部导航栏
     */
    private void resetBottomNavigationBar() {

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

        float density = outMetrics.density;
        int right = (int) (25 * density);
        int bottom = right;

        int colorNormal = getResources().getColor(R.color.colorBottomMenuNormal);
        Rect bounds = new Rect(0, 0, right, bottom);

        menuHome.setTextColor(colorNormal);
        Drawable[] drawables = menuHome.getCompoundDrawables();
        Drawable drawable = getResources().getDrawable(R.drawable.i_home);
        drawable.setBounds(bounds);
        menuHome.setCompoundDrawables(null, drawable, null, null);

        menuOrder.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_order);
        drawable.setBounds(bounds);
        menuOrder.setCompoundDrawables(null, drawable, null, null);

        menuMe.setTextColor(colorNormal);
        drawables = menuHome.getCompoundDrawables();
        drawable = getResources().getDrawable(R.drawable.i_me);
        drawable.setBounds(bounds);
        menuMe.setCompoundDrawables(null, drawable, null, null);
    }

    /**
     * 初始化 第三方SDK
     */
    private void initThirdFrameworks() {

        // 极光推送 初始化
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        // 极光推送 设定别名
        JGUtil.setAlias(MainActivity.this);

        // 讯飞语音 初始化
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID + "=" + XFUtil.APP_ID);

        // 权限设定
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("请授予\"上海交运\"定位权限，否则将无法接收订单").setNegativeButton("禁止", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).setPositiveButton("允许", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                    }
                }
            }).create().show();
        } else {

            // 高德地图 获取位置
            startService(new Intent(MainActivity.this, LocationService.class));
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 高德地图 获取位置
                    startService(new Intent(MainActivity.this, LocationService.class));
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    class MainWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.indexOf("login.html") != -1) {
                mWebView.stopLoading();
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            } else {
                super.onPageStarted(view, url, favicon);
            }
        }
    }

    class MainWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            //return super.onJsConfirm(view, url, message, result);
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle("特别提示")
                    .setMessage(message)
                    .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {
                            result.confirm();
                        }
                    })
                    .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.cancel();
                }
            });

            // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
                    return true;
                }
            });
            // 禁止响应按back键的事件
            // builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }
    }
}
